import json
import requests
from Common.log import MyLog
from Common.yaml_method import YamlMethod


class LarkUserInfo:
    """
    获取飞书用户信息
    """
    def __init__(self):
        self.APP_ID = YamlMethod().read_data('lark_key.yaml')['APP_ID']
        self.APP_SECRET = YamlMethod().read_data('lark_key.yaml')['APP_SECRET']

    def get_access_token(self):
        """
        获取飞书授权登录token
        :return:
        """
        url = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal'
        header = {
            'Content-Type': 'application/json; charset=utf-8'
        }
        body = {
            'app_id': self.APP_ID,
            'app_secret': self.APP_SECRET,
        }
        res = requests.post(url, params=header,data=body)
        return json.loads(res.text)

    def get_user_info(self, pass_code):
        """
        获取飞书返回的的用户信息
        :param pass_code: 飞书授权code
        :return:
        """
        app_access_token = self.get_access_token()['app_access_token']
        url = 'https://open.feishu.cn/open-apis/authen/v1/access_token'
        header = {
            'Authorization': 'Bearer {}'.format(app_access_token),
            'Content-Type': 'application/json; charset=utf-8'
        }
        body = {
            'grant_type': 'authorization_code',
            'code': pass_code,
            'app_id': self.APP_ID,
            'app_secret': self.APP_SECRET,
        }
        res = requests.post(url, headers=header, data=json.dumps(body))
        MyLog().info(json.loads(res.text))
        return json.loads(res.text)